package cn.itsource.ymcc.service.impl;

import cn.itsource.ymcc.domain.Department;
import cn.itsource.ymcc.mapper.DepartmentMapper;
import cn.itsource.ymcc.service.IDepartmentService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Mr.xiang
 * @since 2023-09-10
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;
    @Override
    public List<Department> deptTree() {
        List<Department> departments = departmentMapper.selectList(null);
        Map<Long, Department> collect = departments.stream().collect(Collectors.toMap(Department::getId, Function.identity(), (key1, key2) -> key2));
        ArrayList<Department> departmentArrayList = new ArrayList<>();
        departments.forEach(department->{
            if (department.getParentId() == null){
                departmentArrayList.add(department);
            }else {
                Department one = collect.get(department.getParentId());
                one.getChildren().add(department);
            }
        });

        return departmentArrayList;
    }
}
